package com.google.project.client.ProjectManager;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.gwt.cell.client.ClickableTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasAlignment;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.gwt.view.client.ListDataProvider;
import com.google.project.client.Service.LoginService;
import com.google.project.client.Service.LoginServiceAsync;
import com.google.project.client.Service.ProjectReportService;
import com.google.project.client.Service.ProjectReportServiceAsync;
import com.google.project.client.Service.ProjectService;
import com.google.project.client.Service.ProjectServiceAsync;
import com.google.project.shared.CommonFuntion;
import com.google.project.shared.ProjectDTO;
import com.google.project.shared.ProjectReportDTO;
import com.google.project.shared.UsersDTO;

public class PMProjectReportList extends Composite {

	private static final Binder binder = GWT.create(Binder.class);
	@UiField
	Button btnCreateDailyReport;
	@UiField(provided = true)
	CellTable<ProjectReportDTO> ctbProjectReport = new CellTable<ProjectReportDTO>();
	@UiField
	SimplePager pager;
	@UiField
	Button btnSearch;
	@UiField
	ListBox cboCate;
	@UiField
	DateBox dbFromDate;
	@UiField
	DateBox dbToDate;
	@UiField
	ListBox cbProject;

	interface Binder extends UiBinder<Widget, PMProjectReportList> {
	}

	private final LoginServiceAsync loginService = GWT
			.create(LoginService.class);
	private final ProjectReportServiceAsync projectReportService = GWT
			.create(ProjectReportService.class);
	private final ProjectServiceAsync projService = GWT
			.create(ProjectService.class);

	private List<ProjectReportDTO> listProjectReportDTO = new ArrayList<ProjectReportDTO>();
	UsersDTO currUser = new UsersDTO();

	public PMProjectReportList() {
		initWidget(binder.createAndBindUi(this));
		dbFromDate.setFormat(new DateBox.DefaultFormat(DateTimeFormat.getFormat("dd/MM/yyyy")));
		dbToDate.setFormat(new DateBox.DefaultFormat(DateTimeFormat.getFormat("dd/MM/yyyy")));
		initTable();
		bindData();
		
	}

	public void initCboStatus() {
		cboCate.addItem("---Tất cả---", "-1");
		cboCate.addItem("Chưa Đọc", "2");
		cboCate.addItem("Đã Đọc", "0");
		cboCate.setSelectedIndex(1);
	}

	/***
	 * Fill data to cbProject
	 */
	public void fillCbProject(final String _userId) {
		try {
			projService.getProjectList(new AsyncCallback<List<ProjectDTO>>() {

				@Override
				public void onFailure(Throwable caught) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onSuccess(List<ProjectDTO> result) {
					cbProject.addItem("---Tất cả---", "-1");
					if (result != null && result.size() > 0) {

						for (ProjectDTO proj : result) {
							if (proj.getUserId().equals(_userId)) {
								cbProject.addItem(proj.getProjectName(), proj
										.getProjectID());
							}
						}

					}

				}
			});
		} catch (Exception ex) {
			ex.getMessage();
		}

	}

	// get userInfo from session + new response from DR
	public void bindData() {
		loginService.getCurrentUserDTO(new AsyncCallback<UsersDTO>() {

			@Override
			public void onFailure(Throwable caught) {
			}

			@Override
			public void onSuccess(UsersDTO result) {
				currUser = result;
				fillCbProject(currUser.getUserId()); // fill project to combobox
				getProjectReportByStatus(2); // get report by status=2
				initCboStatus();
			}
		});
	}

	// init ctbReportTaskList
	public void initTable() {
		TextColumn<ProjectReportDTO> indexColumn = new TextColumn<ProjectReportDTO>() {
			@Override
			public String getValue(ProjectReportDTO report) {
				return report.getIndex() + "";
			}
		};
		// ngày báo cáo
		TextColumn<ProjectReportDTO> reportDateColumn = new TextColumn<ProjectReportDTO>() {
			@Override
			public String getValue(ProjectReportDTO report) {
				return CommonFuntion.convertToDate(new Date(report
						.getCreatedOnDate()));
			}
		};
		
		// tên dự án
		Column<ProjectReportDTO, String> projectColumn = new Column<ProjectReportDTO, String>(
				new ClickableTextCell()) {
			@Override
			public String getValue(ProjectReportDTO report) {
				return report.getProjectDTO().getProjectName();
			}
		};
		projectColumn
		.setFieldUpdater(new FieldUpdater<ProjectReportDTO, String>() {

			@Override
			public void update(int index,
					ProjectReportDTO ProjectReportDTO, String value) {
				//update ProjectReport status=0 khi click xem
				if(ProjectReportDTO.getStatus()==2){
					int status=0;
					projectReportService.updateStatusProjectReport(ProjectReportDTO.getId(), status, new AsyncCallback<Void>() {
						@Override
						public void onFailure(Throwable caught) {
							// TODO Auto-generated method stub
							
						}

						@Override
						public void onSuccess(Void result) {
							//Window.alert("Update OK");
							
						}
					});
				}
				
				 PMEntrypoint.get()
				 .PMProjectReportDetail(ProjectReportDTO);
			}
		});
		TextColumn<ProjectReportDTO> statusColumn = new TextColumn<ProjectReportDTO>() {
			@Override
			public String getValue(ProjectReportDTO report) {
				String result = "";
				if (report.getStatus() == 0 || report.getStatus() == 1) {
					result += "Đã đọc";
				} else if (report.getStatus() == 2) {
					result += "Chưa đọc";
				}
				return result;
			}
		};
		ctbProjectReport.setStyleName("ttable");
		ctbProjectReport.addColumn(indexColumn, "STT");
		ctbProjectReport.addColumn(projectColumn, "Dự án");
		ctbProjectReport.addColumn(reportDateColumn, "Báo cáo ngày");
		projectColumn.setCellStyleNames("celltable");
		
		ctbProjectReport
				.getColumn(ctbProjectReport.getColumnIndex(indexColumn))
				.setHorizontalAlignment(HasAlignment.ALIGN_CENTER);
		ctbProjectReport.addColumn(statusColumn, "Tình trạng");

	}

	// load data
	protected void LoadData(List<ProjectReportDTO> reportList) {

		// TODO Auto-generated method stub
		ListDataProvider<ProjectReportDTO> dataProvider = new ListDataProvider<ProjectReportDTO>();

		// Connect the table to the data provider.
		dataProvider.addDataDisplay(ctbProjectReport);

		// Add the data to the data provider, which automatically pushes it to
		// the widget
		int index = 1;
		List<ProjectReportDTO> list = dataProvider.getList();
		for (ProjectReportDTO report : reportList) {
			report.setIndex(index);
			list.add(report);
			index++;
		}
		// SimplePager
		pager.setDisplay(ctbProjectReport);
		pager.setPage(5);
	}

	// get report by status=2 ,userID=pmId
	public void getProjectReportByStatus(final int status) {
		projectReportService
				.getAllProjectReport(new AsyncCallback<List<ProjectReportDTO>>() {

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onSuccess(List<ProjectReportDTO> result) {
						Boolean condition = true;
						for (ProjectReportDTO ProjectReportDTO : result) {
							if (cbProject.getValue(
									cbProject.getSelectedIndex())!=null &&   !cbProject.getValue(
									cbProject.getSelectedIndex()).equals("-1")) {
								String projectID = cbProject.getValue(cbProject
										.getSelectedIndex());
								condition = condition
										&& (ProjectReportDTO.getProjectId()
												.equals(projectID));

							}
							if (cboCate.getValue(cboCate.getSelectedIndex()) != null
									&& Integer.parseInt((cboCate
											.getValue(cboCate
													.getSelectedIndex()))) != -1) {
								condition = condition
										&& (ProjectReportDTO.getStatus() == status);
							}
							if (dbFromDate.getValue() != null) {
								Long fromDate = CommonFuntion
										.removeTime(dbFromDate.getValue());
								condition = condition
										&& (fromDate <= CommonFuntion
												.removeTime(new Date(
														ProjectReportDTO
																.getCreatedOnDate())));
							}
							if (dbToDate.getValue() != null) {
								Long toDate = CommonFuntion.removeTime(dbToDate
										.getValue());
								condition = condition
										&& (CommonFuntion.removeTime(new Date(
												ProjectReportDTO
														.getCreatedOnDate())) < toDate);
							}
							if (condition
									&& ProjectReportDTO.getFromUserID().equals(
											currUser.getUserId())) {
								listProjectReportDTO.add(ProjectReportDTO);
							}
							condition = true;
						}

						if (listProjectReportDTO != null) {
							LoadData(listProjectReportDTO);
						}
					}
				});
	}

	@UiHandler("btnCreateDailyReport")
	void onBtnCreateDailyReportClick(ClickEvent event) {
		PMSelectProject dialog = new PMSelectProject(currUser);
		dialog.setPopupPosition(400, 120);
		dialog.show();
	}

	@UiHandler("cboCate")
	void onCboCateChange(ChangeEvent event) {
		listProjectReportDTO.clear();
	}

	@UiHandler("btnSearch")
	void onBtnSearchClick(ClickEvent event) {
		listProjectReportDTO.clear();
		if (dbFromDate.getValue() != null && dbToDate.getValue() != null) {
			if (dbFromDate.getValue().getTime() > dbToDate.getValue().getTime()) {
				Window.alert("Đến Ngày phải lớn hơn Ngày Trước!");
				listProjectReportDTO.clear();
			} else {
				getProjectReportByStatus(-1);
			}
		} else {
			int value = Integer.parseInt(cboCate.getValue(cboCate
					.getSelectedIndex()));
			if (value == -1) {
				getProjectReportByStatus(-1);
			} else if (value == 0) {
				getProjectReportByStatus(0);
				getProjectReportByStatus(1);
			} else if (value == 2) {
				getProjectReportByStatus(value);
			}
		}

	}

}
